package edu.cs.usask.ca.silver.plugin.rcp.handlers.util;

import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.cs.usask.ca.silver.exceptions.UnableToInitializeStorageException;
import edu.cs.usask.ca.silver.plugin.rcp.Activator;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverSystemMessageEnumerations;
import edu.cs.usask.ca.silver.plugin.rcp.dao.SilverBusinessLogicController;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectView;

/**
 * 
 * This class implements the command to clear storage. The action pops up a
 * dialog to confirm action before proceed. If use confirms the action then
 * current storage is cleared.
 * 
 * TODO: update for multiple storage 
 * @author Yudi Xue
 * 
 */
public class ClearDatabaseHandler extends AbstractHandler {
	private static Logger logger = Logger.getLogger(ClearDatabaseHandler.class);

	/**
	 * this method is the execution of clearing database action. It creates the
	 * appropriate dialog box and waits for the user to press ok or cancel. If
	 * OK s pressed then the database is erased and project viewer is refreshed
	 * after. If CANCEL is pressed then nothing is happened.
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		boolean user_response = MessageDialog.openConfirm(Activator
				.getDefault().getWorkbench().getActiveWorkbenchWindow()
				.getShell(),
				SilverSystemMessageEnumerations.SYSTEM_NO_ROLLBACK_CONFIRM
						.getTitle(),
				SilverSystemMessageEnumerations.SYSTEM_NO_ROLLBACK_CONFIRM
						.getErrorMsg());

		boolean success = false;
		if (user_response) {
			try {
				success = SilverBusinessLogicController.getLocalDerbyStorage()
						.clearStorage();
				ProjectView view = (ProjectView)HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().findView(ProjectView.ID);
				// close all editors without saving
				view.getViewSite().getWorkbenchWindow().getActivePage().closeAllEditors(false);
				// refreshes the entire tree
				view.refresh();
			}
			catch (Exception e) {
				// InvalidStorageException is unlikely to happen
				LoggerReportScheduler.scheduleErrorLogging(logger,"error while clearing database in rcp command handler", e);
			}

		}
		return success;
	}
}
